package com.zmx.patientend.view.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.MessageAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
*时间：2020/5/27 23:24
*功能：
*/
public class MessageActivity extends BaseActivity {

    private RecyclerView reView;
    private SmartRefreshLayout refreshLayout;
    private MessageAdapter adapter;
    private List<com.zmx.patientend.pojo.Message> lists;
    private View mEmptyLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_message;
    }

    @Override
    protected void initViews() {
        setToolbar(R.id.tool_bar);

        MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.unread_message,false);
        mEmptyLayout = findViewById(R.id.empty);
        reView = findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new MessageAdapter(mActivity);
        reView.setAdapter(adapter);
        lists = new ArrayList<>();

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent();
                if (lists.get(listPosition).getType() == 0){

                    intent.setClass(mActivity, ExpertConsultationActivity.class);
                    startActivity(intent);

                }else if (lists.get(listPosition).getType() == 1){

                    intent.setClass(mActivity, MePhysicianActivity.class);
                    startActivity(intent);

                }else if (lists.get(listPosition).getType() == 3){

                    try {

                        JSONObject content = new JSONObject(lists.get(listPosition).getContent());

                        String flow_id = content.getString("notes_id");
                        AlertDialog.Builder builder=new AlertDialog.Builder(mActivity);
                        builder.setTitle("提示：");
                        builder.setMessage("是否要加入该专家团队？");

                        //设置确定按钮
                        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                option(flow_id);
                            }
                        });
                        //设置取消按钮
                        builder.setPositiveButton("容我再想想",null);
                        //显示提示框
                        builder.show();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        });

        // 开启自动加载功能
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            getData();
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            //刷新加载
            refreshLayout.finishLoadMore(true);

        });

        //触发自动刷新
        refreshLayout.autoRefresh();

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        if (object.getInt("code") == 1) {

                            JSONArray array = new JSONArray(object.getString("data"));
                            Gson gson = new Gson();
                            for (int i = 0; i < array.length(); i++) {

                                JSONObject jsonObject = array.getJSONObject(i);
                                com.zmx.patientend.pojo.Message m = gson.fromJson(jsonObject.toString(), com.zmx.patientend.pojo.Message.class);
                                lists.add(m);

                            }

                        }

                        adapter.setListAndNotifyDataSetChanged(lists);//就是设置list然后刷新
                        //刷新加载
                        refreshLayout.finishRefresh(true);
                        if (lists.size() > 0) {

                            mEmptyLayout.setVisibility(View.GONE);

                        } else {

                            mEmptyLayout.setVisibility(View.VISIBLE);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };

    /**
     * 获取所有提问
     */
    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add("10");
        ls.add("1");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "noticeList");
        params.put("data[row]", "1");
        params.put("data[number]", "10");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }


    /**
     * 获取所有提问
     */
    public void option(String notes_id) {

        List<String> ls = new ArrayList<>();
        ls.add(notes_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "option");
        params.put("data[notes_id]", notes_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.patient_follow/entry", params, handler, 2, 404);

    }


}
